package com.jyw.router.hospital.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyw.router.common.exception.ServiceException;
import com.jyw.router.common.utils.DateUtils;
import com.jyw.router.common.utils.StringUtils;
import com.jyw.router.hospital.domain.HospitalInfo;
import com.jyw.router.hospital.domain.vo.RegisterUserVo;
import com.jyw.router.hospital.service.IHospitalInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jyw.router.hospital.mapper.HospitalRegisterUserMapper;
import com.jyw.router.hospital.domain.HospitalRegisterUser;
import com.jyw.router.hospital.service.IHospitalRegisterUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;

/**
 * 注册用户信息Service业务层处理
 *
 * @author shenjun
 * @date 2023-04-17
 */
@Service
@Slf4j
public class HospitalRegisterUserServiceImpl extends ServiceImpl<HospitalRegisterUserMapper, HospitalRegisterUser> implements IHospitalRegisterUserService {
    @Autowired
    private HospitalRegisterUserMapper hospitalRegisterUserMapper;

    @Resource
    private IHospitalInfoService hospitalService;

    /**
     * 查询注册用户信息
     *
     * @param id 注册用户信息主键
     * @return 注册用户信息
     */
    @Override
    public HospitalRegisterUser selectHospitalRegisterUserById(Long id) {
        return hospitalRegisterUserMapper.selectHospitalRegisterUserById(id);
    }

    /**
     * 查询注册用户信息列表
     *
     * @param hospitalRegisterUser 注册用户信息
     * @return 注册用户信息
     */
    @Override
    public List<HospitalRegisterUser> selectHospitalRegisterUserList(HospitalRegisterUser hospitalRegisterUser) {
        return hospitalRegisterUserMapper.selectHospitalRegisterUserList(hospitalRegisterUser);
    }

    /**
     * 新增注册用户信息
     *
     * @param hospitalRegisterUser 注册用户信息
     * @return 结果
     */
    @Override
    public int insertHospitalRegisterUser(HospitalRegisterUser hospitalRegisterUser) {
        hospitalRegisterUser.setCreateTime(LocalDateTime.now());
        return hospitalRegisterUserMapper.insertHospitalRegisterUser(hospitalRegisterUser);
    }

    /**
     * 修改注册用户信息
     *
     * @param hospitalRegisterUser 注册用户信息
     * @return 结果
     */
    @Override
    public int updateHospitalRegisterUser(HospitalRegisterUser hospitalRegisterUser) {
        hospitalRegisterUser.setUpdateTime(LocalDateTime.now());
        return hospitalRegisterUserMapper.updateHospitalRegisterUser(hospitalRegisterUser);
    }

    /**
     * 批量删除注册用户信息
     *
     * @param ids 需要删除的注册用户信息主键
     * @return 结果
     */
    @Override
    public int deleteHospitalRegisterUserByIds(Long[] ids) {
        return hospitalRegisterUserMapper.deleteHospitalRegisterUserByIds(ids);
    }

    /**
     * 删除注册用户信息信息
     *
     * @param id 注册用户信息主键
     * @return 结果
     */
    @Override
    public int deleteHospitalRegisterUserById(Long id) {
        return hospitalRegisterUserMapper.deleteHospitalRegisterUserById(id);
    }

    @Override
    public void disabled(Long id) {
        HospitalRegisterUser user = getById(id);
        if (ObjectUtils.isEmpty(user)) {
            throw new ServiceException("用户信息不存在,禁用失败");
        }
        updateById(new HospitalRegisterUser() {{
            setId(id);
            setRecordState(0);
            setUpdateTime(LocalDateTime.now());
        }});
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void enable(Long id) {
        HospitalRegisterUser user = getById(id);
        if (ObjectUtils.isEmpty(user)) {
            throw new ServiceException("用户信息不存在,启用失败");
        }
        //检查是否存在该手机号在其他医院启用的信息
        if (!StringUtils.isEmpty(user.getUserPhone())) {
            LambdaQueryWrapper<HospitalRegisterUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper
                    .eq(HospitalRegisterUser::getUserPhone, user.getUserPhone())
                    .eq(HospitalRegisterUser::getRecordState, 1)
                    .ne(HospitalRegisterUser::getId, id);
            HospitalRegisterUser one = getOne(queryWrapper);
            if (!ObjectUtils.isEmpty(one)) {
                //如果其他禁用信息不为空,那么禁用该用户信息
                disabled(one.getId());
            }

//            启用该医院信息
            updateById(new HospitalRegisterUser() {{
                setId(id);
                setRecordState(1);
                setUpdateTime(LocalDateTime.now());
            }});
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void registerUser(RegisterUserVo registerUser) {
        //根据医院公钥和私钥获取医院信息
        HospitalInfo hospital = hospitalService.getHospitalByKey(new HospitalInfo() {{
            setServerKey(registerUser.getServerKey());
            setServerSecret(registerUser.getServerSecret());
        }});
        if(ObjectUtils.isEmpty(hospital)){
            throw new ServiceException("系统密钥错误,注册用户失败");
        }
        if(hospital.getRecordState().equals(0)){
            throw new ServiceException("医院未启用,注册用户失败");
        }
        //根据用户电话号与医院标识判断用户是否存在系统中
        LambdaQueryWrapper<HospitalRegisterUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HospitalRegisterUser::getUserPhone, registerUser.getUserPhone())
                .eq(HospitalRegisterUser::getHospitalId, hospital.getId());
        HospitalRegisterUser user = getOne(queryWrapper);
        if(ObjectUtils.isEmpty(user)){
            //用户不存在,新增用户
            log.info("用户注册,用户不存在,注册新用户.医院信息:{},注册用户信息:{}",hospital,registerUser);
            user = registerUser.buildUser(hospital);
            save(user);
        }else{
            if(!user.getUserId().equals(registerUser.getUserId())){
                log.error("用户注册,用户的系统标识发生变化,医院信息:{},注册用户信息:{},用户原本信息:{}",hospital,registerUser,user);
                //将用户标识重置
                HospitalRegisterUser finalUser = user;
                updateById(new HospitalRegisterUser(){{setId(finalUser.getId());setUserId(registerUser.getUserId());setUpdateTime(LocalDateTime.now());}});
            }
        }
        //将用户激活
        enable(user.getId());

    }

    @Override
    public HospitalRegisterUser getUserByPhone(String phone) {
        LambdaQueryWrapper<HospitalRegisterUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HospitalRegisterUser::getUserPhone,phone);
        queryWrapper.eq(HospitalRegisterUser::getRecordState,1);
        return getOne(queryWrapper);
    }
}
